package com.goldmantis.activemq.ch3.queue;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class MQQueueSessionConsumer2 {

    private static String brokerURL = "tcp://localhost:51616";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient Session session;
    
    private String jobs[] = new String[]{"suspend", "delete"};
    
    public MQQueueSessionConsumer2() throws JMSException {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection();
    	connection.setClientID("consumer2");
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }    
    
    public static void main(String[] args) throws JMSException {
    	MQQueueSessionConsumer2 consumer = new MQQueueSessionConsumer2();
		Queue destination = consumer.getSession().createQueue("JOBS.1?consumer.prefetchSize=0");
		MessageConsumer messageConsumer = consumer.getSession().createConsumer(destination);
		messageConsumer.setMessageListener(new MessageListener(){
			@Override
			public void onMessage(Message message){
				try {
					if(message instanceof TextMessage){
						System.out.println("consumer收到信息:"+((TextMessage)message).getText());
					}
				} catch (JMSException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		//messageConsumer.setMessageListener(new Listener("1"));
    }
	
	public Session getSession() {
		return session;
	}
}
